package com.jieshen.servlet;

import com.jieshen.Path;
import com.jieshen.utils.DownLoadUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@WebServlet("/downLoadServlet")
public class downLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取要下载的文件名
        String fileName = request.getParameter("filename");
        String downloadFileName = Path.upLoadFilePath + fileName;
        System.out.println(downloadFileName);

        // 读取要下载的文件内容
        ServletContext servletContext = this.getServletContext();

        //获取要返回的文件类型
        String mimeType = servletContext.getMimeType(downloadFileName);
        System.out.println(mimeType);
        //* 在回传前，通过响应头告诉客户端返回的数据类型
        response.setContentType(mimeType);

        //* 告诉客户端收到的数据用于下载(使用响应头)
        // 根据不同浏览器对文件名编码
        String agent = request.getHeader("user-agent");
        fileName = DownLoadUtils.getFileName(agent,fileName);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        //InputStream resourceAsStream = servletContext.getResourceAsStream(downloadFileName);
        FileInputStream fis = new FileInputStream(downloadFileName);
        //获取响应的输出流
        OutputStream outputStream = response.getOutputStream();
        //读取输入流中全部的数据，复制给输出流，输出给客户端
        IOUtils.copy(fis, outputStream);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
